package tasks.leetcode;

public class TaskLongestCommonPrefix {
    public static void main(String[] args) {
        String s = new TaskLongestCommonPrefix().longestCommonPrefix(new String[]{"flower", "flow", "flight"});
        System.out.println(s);
    }

    public String longestCommonPrefix(String[] strs) {
        if (strs == null) {
            return null;
        }
        if (strs.length == 0) {
            return strs[0];
        }

        String prefix = strs[0];

        for (int i = 1; i < strs.length; i++) {
            prefix = getPrefix(prefix, strs[i]);
            if (prefix.length() == 0) {
                break;
            }
        }
        return prefix;
    }

    private String getPrefix(String prefix, String str) {
        int index = 0;
        int maxLength = Math.min(prefix.length(), str.length());
        for (int i = 0; i < maxLength; i++) {
            if (prefix.charAt(i) == str.charAt(i)) {
                index++;
            } else {
                break;
            }
        }
        return prefix.substring(0, index);
    }
}
